package com.uetoken.cn.activity;

import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.TextView;

import com.blankj.utilcode.util.AppUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.SPUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.gson.Gson;
import com.pcn.helper.PCNHelper;
import com.qmuiteam.qmui.util.QMUIStatusBarHelper;
import com.qmuiteam.qmui.widget.QMUITopBar;
import com.uetoken.cn.R;
import com.uetoken.cn.adapter.BindAccountAdapter;
import com.uetoken.cn.base.BaseActivity;
import com.uetoken.cn.base.MyApplication;
import com.uetoken.cn.bean.BindAccountBean;
import com.uetoken.cn.bean.MsgBean;
import com.uetoken.cn.common.ApiHelper;
import com.uetoken.cn.common.Constant;
import com.uetoken.cn.manager.UEDataManager;
import com.uetoken.cn.network.OkHttpUtils;
import com.uetoken.cn.network.Params;
import com.uetoken.cn.network.WebResponse;
import com.umeng.socialize.UMAuthListener;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.bean.SHARE_MEDIA;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;

/**
 * author : hejunming
 * e-mail : 925379434@qq.com
 * date   : 2018/10/30 14:30
 */
public class BindAccountSettingActivity extends BaseActivity implements WebResponse {

    @BindView(R.id.topbar)
    QMUITopBar mTopbar;
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.bindProblemTv)
    TextView bindProblemTv;

    /**
     * 请求查询用户所有第三方账号绑定状态请求码
     */
    private static final int REQUEST_NETWORK_QUERY = 10;
    /**
     * 绑定第三方账号请求码
     */
    private static final int REQUEST_NETWORK_BINDING = 20;
    /**
     * 解绑第三方账号请求码
     */
    private static final int REQUEST_NETWORK_UNBIND = 30;

    /**
     * 第三方账号登录类型：0=UE,1-QQ、2-微信、3-微博、4-Pcn、5-优谷 ,
     */
    private int opentype = 0;
    private HashMap<String, Integer> mPlatformMap;
    private SHARE_MEDIA shareMedia = null;
    private String uid = "";
    private String appname = "";
    private String toUri = "";
    private String packageName = "";
    private int positions;
    private String nodeid;
    private boolean isBind;
    private BindAccountAdapter bindAccountAdapter;
    private BindAccountBean bindAccountBean;

    @Override
    public int getLayoutId() {
        return R.layout.activity_bind_account_setting;
    }

    @Override
    public void initView() {

    }

    @Override
    public void initData() {
        // 沉浸式状态栏
        QMUIStatusBarHelper.translucent(this);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            QMUIStatusBarHelper.setStatusBarLightMode(this);
        }
        ButterKnife.bind(this);
        MyApplication.getInstance().setHandler(mHandler);
        initTopBar();
        nodeid = SPUtils.getInstance(Constant.UE_TOKEN_PREFERENCE_USER_INFO).getString(Constant.SP_NODE_ID, "");
        queryBindingState();
        mPlatformMap = UEDataManager.getInstance().getOpensType();
    }

    @Override
    public void init() {

    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        uid = intent.getStringExtra("nodeCode");
        toThirdpartyLogin();
    }

    private void toThirdpartyLogin() {
        if (TextUtils.isEmpty(uid)) {
            ToastUtils.showShort(R.string.str_authorization_failed);
        } else {
            bindOrUnbind(isBind);
        }
    }

    private void updateView() {
        recyclerView.setNestedScrollingEnabled(false);
        recyclerView.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
        bindAccountAdapter = new BindAccountAdapter(R.layout.item_me, bindAccountBean.getData());
        recyclerView.setAdapter(bindAccountAdapter);
        bindAccountAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                positions = position;
                //opentype (integer, optional): 绑定的第三方账号类型：1-QQ、2-微信、3-微博、4-Pcn、5-优谷 ,
                opentype = bindAccountAdapter.getItem(position).getOpentype();
                //账号绑定的状态：0-未绑定、1-绑定
                int status = bindAccountAdapter.getItem(position).getStatus();

                if (opentype == 1) {
                    appname = "QQ";
                    shareMedia = SHARE_MEDIA.QQ;
                } else if (opentype == 2) {
                    appname = "WEIXIN";
                    shareMedia = SHARE_MEDIA.WEIXIN;
                } else if (opentype == 3) {
                    appname = "SINA";
                    shareMedia = SHARE_MEDIA.SINA;
                } else if (opentype == 4) {
                    shareMedia = null;
                    appname = "PCN";
                    packageName = "com.scce.pcn";
                    toUri = "pcn://ue?actionType=4000";
                } else if (opentype == 5) {
                    shareMedia = null;
                    appname = "YOUGU";
                    packageName = "cn.com.yg";
                    toUri = "yougu://ue?actionType=4000";
                } else {
                    shareMedia = null;
                    appname = "";
                    packageName = "";
                    toUri = "";
                }
                if (status == 1) {
                    isBind = false;
                    if (shareMedia == null) {
                        showLoading();
                        setUnbind();
                    } else {
                        UMShareAPI.get(BindAccountSettingActivity.this).deleteOauth(BindAccountSettingActivity.this, shareMedia, authListener);
                    }
                } else {
                    isBind = true;
                    if (shareMedia == null) {
                        SPUtils.getInstance(Constant.UE_TOKEN_PREFERENCE_OTHER_INFO).put(Constant.THRID_APP_BIND, true);
                        showLoading();
                        if ("PCN".equals(appname)) {
                            if (AppUtils.isAppInstalled("com.scce.pcn")) {
                                PCNHelper.toAuthorization(BindAccountSettingActivity.this, null, "tNdWItFPQeudTDslFXfU", "ue");
                            } else {
                                dissmissDialog();
                            }

                        } else {
                            toThirdpartyAPP(packageName, toUri);
                        }
                    } else {
                        UMShareAPI.get(BindAccountSettingActivity.this).getPlatformInfo(BindAccountSettingActivity.this, shareMedia, authListener);
                    }
                }
            }
        });
    }

    /**
     * 启动Pcn、优谷，授权获取nodeCode
     */
    private void toThirdpartyAPP(String packageName, String uri) {
        if (AppUtils.isAppInstalled(packageName)) {
            //安装了优谷程序,则跳转到优谷app进行授权
            Intent intentToAPP = new Intent();
            intentToAPP.setData(Uri.parse(uri));
            startActivity(intentToAPP);
        } else {
            dissmissDialog();
            ToastUtils.showShort(getResources().getString(R.string.str_do_not_install)
                    + ("YOUGU".equals(appname) ? getResources().getString(R.string.str_yg) : appname));
        }
    }

    UMAuthListener authListener = new UMAuthListener() {
        /**
         * @desc 授权开始的回调
         * @param platform 平台名称
         */
        @Override
        public void onStart(SHARE_MEDIA platform) {
            showLoading();
        }

        /**
         * @desc 授权成功的回调
         * @param platform 平台名称
         * @param action 行为序号，开发者用不上
         * @param data 用户资料返回
         */
        @Override
        public void onComplete(SHARE_MEDIA platform, int action, Map<String, String> data) {
            //成功了
            if (data != null) {
                uid = data.get("uid");
                isBind = true;
            } else {
                isBind = false;
            }
            bindOrUnbind(isBind);
        }

        /**
         * @desc 授权失败的回调
         * @param platform 平台名称
         * @param action 行为序号，开发者用不上
         * @param t 错误原因
         */
        @Override
        public void onError(SHARE_MEDIA platform, int action, Throwable t) {
            //失败
            dissmissDialog();
            ToastUtils.showShort(t.getMessage());
        }

        /**
         * @desc 授权取消的回调
         * @param platform 平台名称
         * @param action 行为序号，开发者用不上
         */
        @Override
        public void onCancel(SHARE_MEDIA platform, int action) {
            LogUtils.dTag("BindAccountSettingActivity==", platform + " :" + " onCancel = " + action);
            //取消了
            dissmissDialog();
            ToastUtils.showShort(R.string.str_user_cancelled);
        }
    };

    private void initTopBar() {
        mTopbar.setTitle(R.string.str_bind_account_setting);
        mTopbar.addLeftImageButton(R.drawable.ic_back, R.id.qmui_topbar_item_left_back).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }

    private void bindOrUnbind(boolean isBind) {
        if (isBind) {
            setBinding();
        } else {
            setUnbind();
        }
    }

    @Override
    public void onSuccessResponse(Call call, String response, int requestCode) throws IOException {
        LogUtils.dTag("账号绑定===", "requestCode = " + requestCode + " response = " + response);
        switch (requestCode) {
            case REQUEST_NETWORK_QUERY:
                dissmissDialog();
                bindAccountBean = new Gson().fromJson(response, BindAccountBean.class);
                if (bindAccountBean.getResult() > 0) {
                    updateView();
                } else {
                    ToastUtils.showShort(bindAccountBean.getMessage());
                }
                break;
            case REQUEST_NETWORK_BINDING:
                dissmissDialog();
                MsgBean bind_msgBean = new Gson().fromJson(response, MsgBean.class);
                if (bind_msgBean.getResult() > 0) {
                    BindAccountBean.DataBean bind_dataBean = bindAccountBean.getData().get(positions);
                    bind_dataBean.setStatus(1);
                    bindAccountAdapter.notifyItemChanged(positions);
                }
                ToastUtils.showShort(bind_msgBean.getMessage());

                break;
            case REQUEST_NETWORK_UNBIND:
                dissmissDialog();
                MsgBean unbind_msgBean = new Gson().fromJson(response, MsgBean.class);
                ToastUtils.showShort(unbind_msgBean.getMessage());
                BindAccountBean.DataBean unbind_dataBean = bindAccountBean.getData().get(positions);
                unbind_dataBean.setStatus(0);
                bindAccountAdapter.notifyItemChanged(positions);
                break;
        }
    }

    @Override
    public void onFailResponse(Call call, IOException e, int requestCode) {
        dissmissDialog();
        ToastUtils.showShort(e.getMessage());
    }

    @OnClick({R.id.bindProblemTv})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.bindProblemTv:
                break;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        UMShareAPI.get(this).release();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data);
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        UMShareAPI.get(this).onSaveInstanceState(outState);
    }

    /**
     * 查询用户所有第三方账号绑定状态
     */
    private void queryBindingState() {
        showLoading();
        OkHttpUtils.getInstance().getStringWithParam(this, ApiHelper.getQueryThirdpartyBindStateUrl(), REQUEST_NETWORK_QUERY,
                Params.getQueryBindThirdpartyParams(nodeid));
    }

    /**
     * 绑定第三方账号
     */
    private void setBinding() {
        OkHttpUtils.getInstance().getStringWithParam(this, ApiHelper.getBindThirdpartyUrl(), REQUEST_NETWORK_BINDING,
                Params.getBindThirdpartyParams(nodeid, mPlatformMap.get(appname) + "", uid));
    }

    /**
     * 解绑第三方账号
     */
    private void setUnbind() {
        OkHttpUtils.getInstance().getStringWithParam(this, ApiHelper.getUnbundleThirdpartyUrl(), REQUEST_NETWORK_UNBIND,
                Params.getBindThirdpartyParams(nodeid, mPlatformMap.get(appname) + ""));
    }

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1000:
                    uid = (String) msg.obj;
                    if (TextUtils.isEmpty(uid)) {
                        ToastUtils.showShort(R.string.str_authorization_failed);
                    } else {
                        bindOrUnbind(isBind);
                    }
                    break;
            }
        }
    };
}
